<template>
  <el-card class="box-card el-card-flex">
    <div slot="header" class="clearfix">
      <span>
        <i class="el-icon-medal"></i>
        角色管理
      </span>
    </div>
    <!-- 表单 -->
    <div class="text item">
      <el-form :inline="true" :model="formSearch" class="demo-form-inline" @submit.native.prevent>
        <el-form-item label="">
          <el-input clearable v-model="formSearch.fuzzyfield" placeholder="请输入角色编码/名称" style="width:240px;"
            @keyup.enter.native="getRoleList" @clear="getRoleList">
            <el-button slot="append" icon="el-icon-search" @click="getRoleList"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchDialog">
            高级查询
            <i class="el-icon-magic-stick"></i>
          </el-button>
        </el-form-item>
        <el-form-item style="float:right">
          <el-button @click="roleDialog" type="primary" plain>
            新增
            <i class="el-icon-plus"></i>
          </el-button>
        </el-form-item>
      </el-form>
      <!-- tabel表格 -->
      <div class="el-flex el-box-column">
        <el-table ref="roleTable" height="100%" style="width: 100%" border stripe :data="roleDatas">
          <el-table-column min-width="100px" sortable show-overflow-tooltip prop="roleCode" label="角色编码"></el-table-column>
          <el-table-column min-width="100px" sortable show-overflow-tooltip prop="roleName" label="角色名称"></el-table-column>
          <el-table-column min-width="100px" sortable show-overflow-tooltip prop="roleType" label="角色类型"></el-table-column>
          <el-table-column min-width="120px" sortable show-overflow-tooltip prop="roleDesc" label="角色描述"></el-table-column>
          <el-table-column min-width="100px" sortable show-overflow-tooltip prop="domainName" label="所属系统"></el-table-column>
          <el-table-column min-width="100px" sortable show-overflow-tooltip prop="createdByName" label="创建人" align="center"></el-table-column>
          <el-table-column sortable show-overflow-tooltip label="操作" align="center" fixed="right" width="150px">
            <template slot-scope="scope">
              <el-button class="td-btn-icon" type="text" title="修改角色" @click="roleEditDialog(scope.row)"><i class="el-icon-edit"></i></el-button>
              <el-button @click="giveFuncEvt(scope.row.roleId)" class="td-btn-icon" type="text" title="授权功能"><i class="el-icon-medal"></i></el-button>
              <el-button class="td-btn-icon" type="text" title="删除角色" @click="roleDelRow(scope.row)"><i class="el-icon-delete"></i></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="pageSize"
        :current-page="currentPage" @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
    </div>
    <!-- 查询抽屉-->
    <el-drawer title="高级查询" :visible.sync="searchDialogVisible" direction="rtl" custom-class="demo-drawer">
      <div class="el-box-column" style="height: 100%;">
        <el-form :model="roleSearchForm" ref="roleForm" label-width="100px" class="el-flex el-over-auto">
          <el-form-item label="角色名称" prop="roleName">
            <el-col :span="16">
              <el-input placeholder="请输入角色名称" v-model="roleSearchForm.roleName"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="角色编码" prop="roleCode">
            <el-col :span="18">
              <el-input placeholder="请输入角色编码" v-model="roleSearchForm.roleCode"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="所属系统">
            <el-col :span="16">
              <el-select v-model="roleSearchForm.domainId" placeholder="请选择域信息">
                <el-option v-for="item in domainOPtions" :key="item.domainId" :label="item.domainName" :value="item.domainId">
                </el-option>
              </el-select>
            </el-col>
          </el-form-item>
          <el-form-item label="角色描述">
            <el-col :span="20">
              <el-input type="textarea" placeholder="请输入角色描述" v-model="roleSearchForm.roleDesc"></el-input>
            </el-col>
          </el-form-item>
        </el-form>
        <div style="text-align: right;margin-bottom: 10px;padding-right:10px;">
          <el-button type="primary" @click="getRoleList">
            确定
            <i class="el-icon-document-checked el-icon--right"></i>
          </el-button>
          <el-button @click="searchDialogVisible = false">
            取消
            <i class="el-icon-refresh-left"></i>
          </el-button>

        </div>
      </div>
    </el-drawer>
    <!-- 角色新增编辑弹窗 -->
    <el-dialog title="角色信息" :visible.sync="roleDialogVisible" :close-on-click-modal="false" :close-on-press-escape="false"
      @close="roleDialogCloseEvt">
      <el-form :model="roleForm" ref="roleForm" label-width="100px">
        <el-form-item label="角色名称" prop="roleName" :rules="[
						{
							required: true,
							message: '角色名称不能为空'
						}
					]">
          <el-col :span="10">
            <el-input placeholder="请输入角色名称" v-model="roleForm.roleName"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="角色编码" prop="roleCode" :rules="[
						{
							required: true,
							message: '角色编码不能为空'
						}
					]">
          <el-col :span="12">
            <el-input :readonly="roleCodeReadonly" placeholder="请输入角色编码" v-model="roleForm.roleCode"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="角色类型" prop="roleType">
          <el-col :span="24">
            <el-radio-group v-model="roleForm.roleType">
              <el-radio label="一般管理员" border></el-radio>
              <el-radio label="普通角色" border></el-radio>
            </el-radio-group>
          </el-col>
        </el-form-item>
        <el-form-item label="所属系统">
          <el-select v-model="roleForm.domainId" placeholder="请选择所属系统">
            <el-option v-for="item in domainOPtions" :key="item.domainId" :label="item.domainName" :value="item.domainId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-col :span="18">
            <el-input placeholder="请输入角色描述" type="textarea" v-model="roleForm.roleDesc"></el-input>
          </el-col>

        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveAndGiveFuncEvt">
          授权功能
          <i class="el-icon-medal el-icon--right"></i>
        </el-button>
        <el-button type="primary" @click="roleSaveEvt">
          保存
          <i class="el-icon-document-checked el-icon--right"></i>
        </el-button>
        <el-button type="danger" @click="roleDialogVisible = false">
          关闭
          <i class="el-icon-close"></i>
        </el-button>
      </div>
    </el-dialog>
  </el-card>
</template>
<script>
  import {
    Dialog,
    Drawer,
    Table,
    TableColumn,
    Pagination,
    MessageBox,
    Message
  } from 'element-ui';
  export default {
    components: {
      'el-dialog': Dialog, // 对话框
      'el-drawer': Drawer, // 对话框
      'el-table': Table, // 表格
      'el-table-column': TableColumn, // 表格列
      'el-pagination': Pagination // 分页
    },
    data() {
      //角色表单初始化默认值
      let roleInitVal = {
        "domainId": "",
        "roleCode": "",
        "roleDesc": "",
        "roleName": ""
      };
      return {
        total: 0,
        pageSize: 20, //每页展示条数
        currentPage: 1, //默认显示页数
        formSearch: {}, //查询参数
        //角色高级查询条件
        roleSearchForm: JSON.parse(JSON.stringify(roleInitVal)),
        //角色表单默认值，用于重置表单
        roleInitVal: JSON.parse(JSON.stringify(roleInitVal)),
        //角色表单项-新增修改
        roleForm: JSON.parse(JSON.stringify(roleInitVal)),
        roleCodeReadonly: false, //角色编码是否只读
        domainOPtions: [],
        //表格数据源
        roleDatas: [],
        roleDialogVisible: false, //角色编辑弹窗
        searchDialogVisible: false, //高级查询弹窗
        funcCheckedIds: [] //选中的功能节点id合集
      };
    },
    methods: {
      // 改变当前页条数
      handleSizeChange(val) {
        this.pageSize = val
        this.getRoleList() //刷新表格
      },
      // 切换页数
      handleCurrentChange(val) {
        this.currentPage = val
        this.getRoleList() //刷新表格
      },
      /* 过滤无效数据*/
      filterInvalid(dataSource) {
        let validData = {};
        let jsonData = JSON.stringify(dataSource);
        for (let k in dataSource) {
          let data = dataSource[k];
          if (data != "" && data != null && data != undefined && jsonData != "{}" && jsonData != "[]") {
            validData[k] = data;
          }
        }
        return validData;
      },
      // 删除数据
      roleDelRow(row) {
        MessageBox.confirm('您确定要删除这条数据吗?').then(() => {
          this.axios.delete(`/role/${row.roleId}`).then(res => {
            if (res.data.code != 10000) return;
            Message.success(res.data.msg); //成功提示
            this.getRoleList();
          });
        });
      },
      /* 开启角色新增弹窗 */
      roleDialog() {
        this.roleDialogVisible = true;
        this.roleCodeReadonly = false; //新增时，角色编码可写
      },
      /* 开启角色编辑弹窗 */
      roleEditDialog(row) {
        this.roleDialogVisible = true;
        this.roleCodeReadonly = true; //编辑时，角色编码只读
        this.roleForm = JSON.parse(JSON.stringify(row));
      },
      /* 开启高级查询弹窗 */
      searchDialog() {
        this.searchDialogVisible = true;
      },
      /* 角色弹窗关闭事件，主要用于清空表单和校验 */
      roleDialogCloseEvt() {
        this.$refs.roleForm.resetFields(); //重置校验
        this.roleForm = JSON.parse(JSON.stringify(this.roleInitVal)); //重置为初始值
      },
      /* 角色保存事件 */
      roleSaveEvt() {
        this.$refs.roleForm.validate(valid => {
          if (!valid) return false;
          let sendDatas = this.filterInvalid({
            roleId: this.roleForm.roleId,
            roleName: this.roleForm.roleName,
            roleCode: this.roleForm.roleCode,
            roleType: this.roleForm.roleType,
            domainId: this.roleForm.domainId,
            roleDesc: this.roleForm.roleDesc
          }); //过滤无效参数
          this.axios.put('/role', sendDatas).then(res => {
            if (res.data.code != 10000) return;
            Message.success('角色保存成功'); //成功提示
            this.roleDialogVisible = false; //关闭编辑角色弹窗
            this.getRoleList(); //刷新表格
          })
        });
      },
      /*跳转到角色绑定功能路由组件*/
      giveFuncEvt(roleId) {
        //this.multiRouters是全局提供的自动添加多级路由的方法
        this.$router.addRoutes(this.multiRouters([{
          path: 'roleBindFun',
          name: 'roleBindFun', //自定义name名称
          component: () => import('@/views/authority/roleManage/roleBindFun'),
          meta: {
            title: '角色绑定功能'
          }
        }]));
        this.$router.push({
          name: "layout_frame_roleBindFun", //顶部导航+侧边导航
          //name:"layout_roleBindFun",//顶部导航
          //name:"frame_roleBindFun"//侧边导航
          //name: "roleBindFun",//独立页面
          params: {
            roleId: roleId
          }
        })
      },
      saveAndGiveFuncEvt() {
        this.$refs.roleForm.validate(valid => {
          if (!valid) return false;
          let sendDatas = this.filterInvalid({
            roleId: this.roleForm.roleId,
            roleName: this.roleForm.roleName,
            roleCode: this.roleForm.roleCode,
            domainId: this.roleForm.domainId,
            roleDesc: this.roleForm.roleDesc
          }); //过滤无效参数
          this.axios.put('/role', sendDatas).then(res => {
            if (res.data.code != 10000) return;
            this.roleDialogVisible = false;
            this.getRoleList(); //刷新表格
            this.roleForm.roleId = res.data.data;
            setTimeout(() => {
              this.giveFuncEvt(res.data.data);
            }, 0);
          })
        });
      },
      /* 获取角色列表*/
      getRoleList() {
        let sendDatas = {
          page: this.currentPage,
          size: this.pageSize
        };
        if (this.searchDialogVisible) { //高级查询
          sendDatas.type = 2;
          Object.assign(sendDatas, this.roleSearchForm)
          this.searchDialogVisible = false;
        } else { //模糊查询
          sendDatas.type = 1;
          let fuzzyfield = this.formSearch.fuzzyfield;
          if (!fuzzyfield) fuzzyfield = " ";
          sendDatas.roleName = fuzzyfield;
          sendDatas.roleCode = fuzzyfield;
        }
        sendDatas = this.filterInvalid(sendDatas); //过滤无效数据
        this.axios.get('/role/userCreateRole', {
          params: sendDatas
        }).then(res => {
          if (res.data.code != 10000) return;
          this.total = res.data.data.total
          this.roleDatas = res.data.data.records
          setTimeout(() => {
            this.$refs.roleTable.doLayout() //重绘表格宽度，解决表头对不齐的问题
          }, 0);
        })
      },
      /* 获取系统下拉数据源 */
      getDomainItems() {
        this.axios.post('/ccmsDomainAuth/getDomainAuth').then(res => {
          if (res.data.code != 10000) return;
          this.domainOPtions = res.data.data;
        });
      }
    },
    created() {
      this.getRoleList(); //获取角色列表
      this.getDomainItems(); //获取系统下拉项
      window.onresize = () => {
        this.$refs.roleTable.doLayout() //监听窗口变化，重绘表格布局
      }
    }
  };
</script>
<style lang="scss">
  .checkbox-head {
    text-align: right;
    padding-right: 5px;
  }

  .checkbox-li {
    float: left;
    width: 180px;
    height: 88px;
    padding: 0 0 5px 5px;
    margin: 0 10px 10px 0;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    box-sizing: border-box;
  }

  .checkbox-label {
    float: left;
    margin: 0 5px 5px 0;
    position: relative;
  }

  .checkbox-label>span {
    float: left;
    height: 20px;
    line-height: 20px;
    border: 1px solid #dcdfe6;
    border-radius: 20px;
    padding: 0 8px;
    box-sizing: border-box;
    font-size: 10px;
    background: rgb(245, 245, 245);
    cursor: pointer;
  }

  .checkbox-label:hover span {
    background: rgb(235, 235, 235);
  }

  .checkbox-check {
    position: absolute;
    visibility: hidden;
    opacity: 0;
  }

  .checkbox-label:focus span,
  .checkbox-label .checkbox-check:checked+span {
    color: #409eff;
    background: #ecf5ff;
    border-color: #b3d8ff;
  }
</style>
